﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Magicodes.WeiChat.Controllers.WebApi
{
    public class DemoController : ApiController
    {
        public class UserDemo
        {
            public int Id { get; set; }
            public string Name { get; set; }

        }
        public static List<UserDemo> DemoData { get; set; }
        public DemoController()
        {
            DemoData = new List<UserDemo>()
            {
                new UserDemo() {Id=1,Name="张三" },
                new UserDemo() {Id=2,Name="李四" },
                new UserDemo() {Id=3,Name="王五" },
                new UserDemo() {Id=4,Name="赵六" },
                new UserDemo() {Id=5,Name="孙七" },
                new UserDemo() {Id=6,Name="周八" },
            };
        }
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok(DemoData);
        }
        /// <summary>
        /// 根据Id获取
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult Get(int id)
        {
            var model = DemoData.FirstOrDefault(p => p.Id == id);
            if (model == null)
            {
                return NotFound();
            }
            return Ok(model);
        }
        [HttpPost]
        public IHttpActionResult Post(UserDemo user)
        {
            if (DemoData.Any(p => p.Name == user.Name))
            {
                return BadRequest("该名称已存在！");
            }
            DemoData.Add(user);
            user.Id = DemoData.Count + 1;
            return Created(Url.Link("DefaultApi", new { controller = "Demo", id = user.Id }), user);
        }
        [HttpPut]
        public IHttpActionResult Put(UserDemo user)
        {
            var model = DemoData.FirstOrDefault(p => p.Id == user.Id);
            if (model == null)
            {
                return NotFound();
            }
            model.Name = user.Name;
            return Ok(model);
        }
        [HttpDelete]
        public IHttpActionResult Delete(UserDemo user)
        {
            var model = DemoData.FirstOrDefault(p => p.Id == user.Id);
            if (model == null)
            {
                return NotFound();
            }
            DemoData.Remove(user);
            return StatusCode(HttpStatusCode.NoContent);
        }
    }
}
